package concurrency.multithreading;

import java.util.concurrent.atomic.AtomicLong;

/**
 * @author xiaoming
 * @version 1.0
 * @date 2019-03-12 13:04
 * volatile不像synchronized的互斥性 (不具有原子性)
 *
 * 一个线程对共享变量进行 10000次i++操作，
 * 另一个线程进行 10000次 i-- 操作
 **/
public class VolatileNotAtomic {
    private static volatile long count  = 0L;
    private static final int NUMBER = 10000;

    public static void main(String[] args) {
        Thread subtractThread = new SubtractThread();
        subtractThread.start();
        for (int i = 0; i < NUMBER; i++) {
            synchronized (VolatileNotAtomic.class) {
                count++;
            }
        }
        // 等待减法线程结束
        while (subtractThread.isAlive()) {}

        System.out.println("count 最终结果: " + count);
        // 不加锁之前结果不一定为0
        //加锁之后每次结果都为0

    }

    private static class SubtractThread extends Thread {
        @Override
        public void run() {
            for (int i = 0; i < NUMBER; i++) {
                synchronized (VolatileNotAtomic.class) {
                    count--;
                }
            }
        }
    }
}
